package handlers

import (
	"encoding/json"
	"engine-ctrl/cache"
	"engine-ctrl/models"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func ArticleAdd(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	if title == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}

	data := models.Article{
		Title:   title,
		Content: content,
	}

	err := models.DB.Debug().Create(&data).Error

	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	//设置缓存
	redis_key := "article_add_" + strconv.Itoa(int(data.ID))

	var article models.Article
	//从mysql中获取数据
	models.DB.Where("id = ?", data.ID).First(&article)
	//转化为json数据
	jsonData, _ := json.Marshal(&article)

	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2) //设置缓存两小时

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return

}

func Del(c *gin.Context) {
	id := c.Query("id")

	err := models.DB.Where("id = ?", id).Delete(&models.Article{}).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}

	redis_key := "article_add_" + id
	cache.Rdb.Del(cache.Ctx, redis_key)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}

func List(c *gin.Context) {
	var article []models.Article

	redis_key := "list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()

	if cacheData == "" {
		models.DB.Debug().Find(&article)

		jsonData, _ := json.Marshal(article)

		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &article)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "列表展示成功",
		"data": article,
	})
	return
}
